package com.liyue.downloadutil;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class UpdateAppManager {
    private static final String FILE_SEPARATOR = "/";
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + FILE_SEPARATOR + "autoupdate" + FILE_SEPARATOR;
    private static final String FILE_NAME = FILE_PATH + "autoupdate.apk";
    private static final int UPDATE_TOKEN = 0x29;
    private static final int INSTALL_TOKEN = 0x31;
    private Context context;
    private String message = "检测到本程序有新版本发布，建议您更新！";
    private String spec = "https://189.ly93.cc/V7bABneueYZb/31325213449827699";
    //    private String json1 = "http://10.0.2.2:8080/update.json";
    String result;
    private String VersionName;//当前版本名
    private int VersionCode;//当前版本号
    //  http://192.168.0.107:8080/app-debug.apk
    // 下载应用的对话框
    private Dialog dialog;
    // 下载应用的进度条
    private ProgressBar progressBar;
    private int curProgress;
    private boolean isCancel;


    public UpdateAppManager(Context context) {
        this.context = context;
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TOKEN:
                    progressBar.setProgress(curProgress);
                    break;

                case INSTALL_TOKEN:
                    Log.d("TAG", "handleMessage: 下载完成");
                    installApp ();
                    break;
            }
        }
    };


    public void showDownloadDialog(int layoutID,int progressBarID) {
        View view = LayoutInflater.from(context).inflate(layoutID, null);
        progressBar = (ProgressBar) view.findViewById(progressBarID);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("软件版本更新");
        builder.setView(view);
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isCancel = true;
            }
        });
        dialog = builder.create();
        dialog.show();
        downloadApp();

    }

    /**
     * 下载新版本应用
     */
    public void downloadApp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                InputStream in = null;
                FileOutputStream out = null;
                HttpURLConnection conn = null;
                try {
                    url = new URL(spec);
                    Log.d("TAG", "run: spec " + spec + "  url: " + url);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestProperty("Accept-Encoding", "identity");    // 加上这句话解决问题
                    conn.connect();

                    in = conn.getInputStream();
                    out = new FileOutputStream(FILE_NAME);
                    byte[] buffer = new byte[1024];

                    long fileLength = conn.getContentLength();
                    Log.d("TAG", "run:  " + fileLength);
                    File filePath = new File(FILE_PATH);
                    if (!filePath.exists()) {
                        filePath.mkdir();
                    }
                    int len = 0;
                    long readedLength = 0l;
                    while ((len = in.read(buffer)) != -1) {
                        // 用户点击“取消”按钮，下载中断
                        if (isCancel) {
                            break;
                        }
                        out.write(buffer, 0, len);
                        readedLength += len;
                        Log.d("TAG", "run: readedLength " + readedLength);
                        curProgress = (int) (((float) readedLength / fileLength) * 100);
                        handler.sendEmptyMessage(UPDATE_TOKEN);
                        if (readedLength >= fileLength) {
                            dialog.dismiss();
                            // 下载完毕，通知安装
                            handler.sendEmptyMessage(INSTALL_TOKEN);
                            break;
                        }
                    }
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);


        if (!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file:/" + appFile.toString()), "application/vnd.android.package-archive");
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());

    }


/*
    public void checkUpdateInfo() {
        gethttpresult (json1);
    }
*/


/*    public void gethttpresult(final String urlStr) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                int IntversionCode;
                try {
                    Looper.prepare();
                    URL url = new URL(urlStr);
                    HttpURLConnection connect = (HttpURLConnection) url.openConnection();
                    connect.setRequestMethod("GET");
                    connect.connect();
                    InputStream input = connect.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(input));
                    String line = null;
                    System.out.println("http状态码" + connect.getResponseCode());
                    StringBuffer sb = new StringBuffer();
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    result = sb.toString();
                    JSONObject jsonObject;
                    jsonObject = new JSONObject(result);
                    System.out.println("run（）" + result);
                    String downloadUrl = jsonObject.optString("downloadUrl");
                    String versionCode = jsonObject.optString("versionCode");
                    String versionDes = jsonObject.optString("versionDes");
                    String versionName = jsonObject.optString("versionName");

                    System.out.println("downloadUrl " + downloadUrl);
                    System.out.println("versionCode " + versionCode);
                    System.out.println("versionDes " + versionDes);


                    try {
                        //获取软件版本号，对应AndroidManifest.xml下android:versionCode
                        VersionCode = context.getPackageManager().
                                getPackageInfo(context.getPackageName(), 0).versionCode;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    try {
                        VersionName = context.getPackageManager().
                                getPackageInfo(context.getPackageName(), 0).versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(context, "当前版本为：" + VersionName, Toast.LENGTH_SHORT).show();

                    try {
                        IntversionCode = Integer.parseInt(versionCode);
                        if (IntversionCode > VersionCode) {
                            new AlertDialog.Builder(context)
                                    .setTitle("软件版本更新")
                                    .setMessage(versionDes)
                                    .setPositiveButton("下载", new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            showDownloadDialog();
                                        }
                                    }).setNegativeButton("以后再说", new OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                        } else {
                            new AlertDialog.Builder(context)
                                    .setTitle("已经是最新版本")
                                    .setPositiveButton("取消", new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();

                                        }
                                    }).show();

                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }//版本号转为int,再比较


                    Looper.loop();

                } catch (Exception e) {

                }
            }

        }).start();
    }*/
}
